import '@/assets/css/common.css';
import { Runtime } from 'wxt/browser';
import { GetGigaResourceMessage, MessageType, OpenOperationInstructionMessage } from '@/config';

export enum Status {
  open = 'open',
  close = 'close',
}
export const operationInstructionStatus = 'operation-instruction-status';
export const operationInstructionName = 'operation-instruction-name';

export interface operationInstructionStatusMessage {
  type: typeof operationInstructionStatus;
  data: {
    status: Status;
  };
}

export default defineContentScript({
  matches: ['<all_urls>'],

  async main(ctx) {
    const ui = createIframeUi(ctx, {
      page: '/operation-instruction-html.html',
      position: 'inline',
      onMount: (wrapper, iframe) => {
        let operationInstructionPort: Runtime.Port | null = null;
        async function handlePort(port: Runtime.Port) {
          operationInstructionPort = port;
          if (port.name === operationInstructionName) {
            port.onMessage.addListener(handlePortMessage);
          }
        }
        async function handlePortMessage(message: operationInstructionStatusMessage) {
          const status = message.data.status;
          if (status === Status.open) {
            wrapper.style.pointerEvents = 'auto';
          } else {
            wrapper.style.pointerEvents = 'none';
          }
        }
        browser.runtime.onConnect.addListener(handlePort);

        // 接受打开使用说明的信号
        async function handleOpenOperationInstruction(message: OpenOperationInstructionMessage) {
          if (message.type === MessageType.openOperationInstruction) {
            if (operationInstructionPort) {
              operationInstructionPort.postMessage({
                type: MessageType.openOperationInstruction,
              });
            }
          }
        }
        browser.runtime.onMessage.addListener(handleOpenOperationInstruction);

        ctx.onInvalidated(() => {
          browser.runtime.onConnect.removeListener(handlePort);
          browser.runtime.onMessage.removeListener(handleOpenOperationInstruction);
        });

        iframe.style.cssText = `
          position: abosulte;
          border: none;
          width: 100vw;
          height: 100vh;
        `;
      },
    });

    // Show UI to user
    ui.mount();
  },
});
